import {type Options, type Column, type Record} from "./type"
import RowColumnSelection from "./RowColumnSelection";
import { getCurrentInstance } from 'vue'
export default class Sort extends RowColumnSelection {
    constructor(options: Options){
        super(options)
        this.internalInstance = getCurrentInstance()
    }
    internalInstance: any;
    sortHandel(column: Column) {
        if (!column.sorter) return;
        this.columns.value.forEach(item => {
            if(item !== column) item.sortOrder = undefined
        });
        
        if(this.selectedState.cells){
            this.sorterBeforeSelectedKeys = undefined;
        } else {
            this.sorterBeforeSelectedKeys = this.getSelectRows().map(row => row[this.props.rowKey]).filter(v => v !== undefined);
        }
        
        const nextSortOrder = column.sortOrder === 'ascend' ? 'descend' : column.sortOrder === 'descend' ? false : 'ascend'
        
        if(typeof column.sorter === 'function') {
            column.sorter(nextSortOrder)
        } else {
            if (column.sortOrder === 'ascend') {
                this.dataSource.value.sort(this.descendHandel(column))
            } else if (column.sortOrder === 'descend'){
                this.restoreSort()
            } else {
                this.sorterBeforeDataKeys = this.dataSource.value.map(row => row[this.props.rowKey]).filter(v => v !== undefined);
                this.dataSource.value.sort(this.ascendHandel(column))
            }
        }
        column.sortOrder = nextSortOrder
        this.internalInstance?.ctx?.$forceUpdate()
    
        // 转换选择行的记录
        if (this.sorterBeforeSelectedKeys?.length) {
            this.resetSelectedState()
            this.selectedState.rows = this.dataSource.value.map((row, rowindex) => {
                if(this.sorterBeforeSelectedKeys?.includes(row[this.props.rowKey])) return rowindex
            }).filter(v => v !== undefined) as number[]
        } else if (this.sorterBeforeSelectedKeys === undefined){
            this.resetSelectedState()
        }
    }

    // 排序前的选择行的key顺序
    sorterBeforeSelectedKeys?: any[]
    // 排序前的key顺序
    private sorterBeforeDataKeys: any[] = []
    // 升序
    private ascendHandel(column: Column){
        return (a: Record, b: Record) => {
            // 空行不参与排序
            if (this.props.keepLastRowEmpty) {
                const lastRow =  this.dataSource.value.at(-1) ?? {}
                const lastRowKey = lastRow[this.props.rowKey];
                if (lastRowKey && a[this.props.rowKey] === lastRowKey ){
                    return 0;
                }
            }
            const param1 = this.getValueByModel(column.dataIndex, a) || '';
            const param2 = this.getValueByModel(column.dataIndex, b) || '';
            return this.sorterComper(param1, param2, 'ascend')
        };
    }
    // 降序
    private descendHandel(column: Column){
        return (a: Record, b: Record) => {
            // 空行不参与排序
            if (this.props.keepLastRowEmpty) {
                const lastRow =  this.dataSource.value.at(-1) ?? {}
                const lastRowKey = lastRow[this.props.rowKey];
                if (lastRowKey && a[this.props.rowKey] === lastRowKey ){
                    return 0;
                }
            }
            const param1 = this.getValueByModel(column.dataIndex, a) || '';
            const param2 = this.getValueByModel(column.dataIndex, b) || '';
            return this.sorterComper(param1, param2, 'descend')
        };
    }
    // 比较函数
    private sorterComper(a: number | string = 0, b: number | string = 0, type: 'ascend' | 'descend'){
        if (typeof a === 'number' && typeof b === 'number') {
            return type === 'ascend' ?  a - b : b - a;
        } else {
            return type === 'ascend' ? a.toString().localeCompare(b.toString()) : b.toString().localeCompare(a.toString())
        }
    }
    // 取消排序
    private restoreSort(){
        let newFragment: any[] = []
        this.dataSource.value.forEach(row => {
            newFragment.push(row) 
            const index = this.sorterBeforeDataKeys.findIndex(key => key === row[this.props.rowKey]);
            if(index >= 0) {
                this.sorterBeforeDataKeys.splice(index, 1, ...newFragment)
                newFragment = []
            }
        })

        if(newFragment.length){
            this.sorterBeforeDataKeys.push(...newFragment);
        }
        
        // 排序前数据（含插入新行数据、不含已删除的数据）
        const data = this.sorterBeforeDataKeys.filter(item => typeof item !== 'string')
        this.dataSource.value.splice(0, this.dataSource.value.length, ...data)
        this.sorterBeforeDataKeys = []
    }
}